package com.shujia.hw;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class InsertUserDataToMysql {
    public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
        File surnameFile = new File("redisCode/data/姓氏.txt");
        File nameFile = new File("redisCode/data/名字.txt");
        RandomUser randomUser = new RandomUser(surnameFile, nameFile);
        // RandomUser构造方法只创建了一次，所以User只有一个，每次往User中修改数据
        // IO流也只创建了一次

//        User oneUser = randomUser.createOneUser(1);
//        System.out.println(oneUser);


        //1、注册驱动
        Class.forName("com.mysql.jdbc.Driver");

        // 2.创建连接
        Properties properties = new Properties();
        properties.load(new FileReader("redisCode/src/main/resources/mysql.properties"));
        String url = properties.getProperty("url");
        String user = properties.getProperty("user");
        String passwd = properties.getProperty("passwd");
        Connection connection = DriverManager.getConnection(url, user, passwd);
        // 注意：Mysql连接通道也只创建一次，不能每次for循环创建一次对象


        // 3.创建操作对象

        Statement statement = connection.createStatement();

        // 4.执行SQL

        int userNum = 100 * 10000;

        for (int i = 0; i < userNum; i++) {
            User oneUser = randomUser.createOneUser(i);
            String sql = "insert into user(id,name,age,accumulate,userClazz) values(%d,'%s',%d,%d,%d)";
            String formatSQL = String.format(sql, oneUser.getId(), oneUser.getName(), oneUser.getAge(), oneUser.getAccumulate(), oneUser.getUserClazz());
            // 影响的行数
            int i1 = statement.executeUpdate(formatSQL);
            if (i1 > 0) {
                System.out.println("成功插入：" + i + "条");
            }
        }


        // 关闭资源
        connection.close();
        randomUser.close();


    }


}
